package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.Const;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.HCustomerManageMapper;
import com.flea.hclv.model.dao.HCustomerPayRecordMapper;
import com.flea.hclv.model.entity.HCustomerManage;
import com.flea.hclv.model.entity.HCustomerPayRecord;
import com.flea.hclv.model.entity.vo.HCustomerManageVo;
import com.flea.hclv.service.HCustomerManageService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.dao.OrgDeptMapper;
import com.flea.system.entity.OrgDept;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @program: project
 * @description: 客户管理
 * @author: shiliqiang
 * @create: 2018-11-10 14:16
 * @version: 1.0
 */
@Service
public class HCustomerManageServiceImpl implements HCustomerManageService {

    @Autowired
    private HCustomerManageMapper hCustomerManageMapper;
    @Autowired
    private HCustomerPayRecordMapper hCustomerPayRecordMapper;
    @Autowired
    private OrgDeptMapper orgDeptMapper;


    @Override
    public ServerResponse<List<OrgDept>> selectAllDept() {
        List<OrgDept> data = Lists.newArrayList();
        List<OrgDept> groups = orgDeptMapper.findByServiceType(HConstant.D_SERVICE_ORG_GROUP);
        if (CollectionUtils.isNotEmpty(groups)){
           for (OrgDept dept : groups){
               if (dept.getDeptLevel().equals(HConstant.ROOT_LEVEL)){
                   data.add(dept);
               }
           }
        }
        List<OrgDept> deptList = orgDeptMapper.findByServiceType(HConstant.D_SERVICE_ORG_SUPPLIER);
        if (CollectionUtils.isNotEmpty(deptList)){
            for (OrgDept dept : deptList){
                if (dept.getDeptLevel().equals(HConstant.ROOT_LEVEL)){
                    data.add(dept);
                }
            }
        }
        return ServerResponse.createBySuccess(data);
    }

    @Override
    public ServerResponse<FleaPage<HCustomerManageVo>> select(String queryName, String queryStartTime, String queryEndTime, String serviceType, int curPage, int pageSize) {
        RowBounds rowBounds = new RowBounds(curPage, pageSize);
        List<OrgDept> deptList=null;
        if (StringUtils.isNotBlank(queryName) || StringUtils.isNotBlank(serviceType)) {
            if (StringUtils.isNotBlank(queryName) && StringUtils.isBlank(serviceType)){
                deptList = orgDeptMapper.findByLikeName(queryName);
                if (CollectionUtils.isEmpty(deptList)){
                    return ServerResponse.createBySuccess();
                }
            }
            if (StringUtils.isBlank(queryName) && StringUtils.isNotBlank(serviceType)){
                deptList = orgDeptMapper.findByServiceType(serviceType);
            }
            if (StringUtils.isNotBlank(queryName) && StringUtils.isNotBlank(serviceType)){
                deptList = orgDeptMapper.findByServiceType(serviceType);
                if (CollectionUtils.isNotEmpty(deptList)){
                    List<OrgDept> deptList1 = Lists.newArrayList();
                    for (OrgDept dept : deptList){
                        if (dept.getDeptName().equals(queryName)){
                            deptList1.add(dept);
                        }
                    }
                    deptList = deptList1;
                    if (CollectionUtils.isEmpty(deptList)){
                        return ServerResponse.createBySuccess();
                    }
                }
            }
        }

        //通过 部门id 找到客户缴费状态信息
        List<HCustomerManage> manageList = hCustomerManageMapper.selectByParams(rowBounds, queryStartTime, queryEndTime, deptList);
        manageList.size();
        //将两个类拼在一起返回页面
        List<HCustomerManageVo> voList = this.assembleCustomerManageVo(manageList);

        FleaPage<HCustomerManage> temp = new FleaPage<>(manageList);
        FleaPage<HCustomerManageVo> voFleaPage = new FleaPage<>();
        voFleaPage.setCurPageData(voList);
        voFleaPage.setCurPage(temp.getCurPage());
        voFleaPage.setAllDataCount((int) temp.getAllDataCount());
        voFleaPage.setPageSize(temp.getPageSize());
        return ServerResponse.createBySuccess(voFleaPage);
    }

    private List<HCustomerManageVo> assembleCustomerManageVo(List<HCustomerManage> manageList) {
        List<HCustomerManageVo> voList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(manageList)) {
            for (HCustomerManage aManageList : manageList) {
                HCustomerManageVo vo = new HCustomerManageVo();
                vo.setDeptId(aManageList.getDeptId());
                OrgDept dept = orgDeptMapper.selectByPrimaryKey(aManageList.getDeptId());
                vo.setDeptCode(dept.getDeptCode());
                vo.setDeptName(dept.getDeptName());
                vo.setServiceType(dept.getServiceType());
                vo.setPersonPhone(aManageList.getPersonPhone());
                vo.setPersonName(aManageList.getPersonName());
                vo.setCustomerManageId(aManageList.getId());
                vo.setCost(aManageList.getCost());
                vo.setStatus(aManageList.getStatus());
                vo.setEndTime(aManageList.getEndTime());
                vo.setStartTime(aManageList.getStartTime());
                voList.add(vo);
            }
            return voList;
        }

        return voList;
    }

    @Override
    public ServerResponse<String> update(String userId, String model) {
        if (StringUtils.isBlank(model)) {
            return ServerResponse.createByErrorMessage("model为空");
        }

        HCustomerManage hCustomerManage = JSON.parseObject(model, HCustomerManage.class);
        if (hCustomerManage == null) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        String customerManageId = JSON.parseObject(model).getString("customerManageId");
        if (StringUtils.isBlank(customerManageId)) {
            return ServerResponse.createByErrorMessage("customerManageId不能为空");
        }
        hCustomerManage.setId(customerManageId);
        int row = hCustomerManageMapper.updateByPrimaryKeySelective(hCustomerManage);
        if (row <= 0) {
            return ServerResponse.createByErrorMessage("客户更新失败");
        }
        return ServerResponse.createBySuccessMessage("客户更新成功");
    }

    @Override
    public ServerResponse<String> saveCustomerPay(String userId, String model) {
        this.save(userId, model);
        if (model == null) {
            ServerResponse.createByErrorMessage("model为空");
        }
        JSONObject jsonObject = JSON.parseObject(model);
        String customerId = jsonObject.getString("id");
        if (StringUtils.isBlank(customerId)) {
            return ServerResponse.createByErrorMessage("id为空");
        }
        String endTime = jsonObject.getString("endTime");
        if (StringUtils.isBlank(endTime)) {
            return ServerResponse.createByErrorMessage("到期时间为空");
        }
        String startTime = jsonObject.getString("startTime");
        if (StringUtils.isBlank(startTime)) {
            return ServerResponse.createByErrorMessage("开始时间为空");
        }
        String cost = jsonObject.getString("cost");
        if (StringUtils.isBlank(cost)) {
            return ServerResponse.createByErrorMessage("费用为空");
        }
        HCustomerPayRecord record = new HCustomerPayRecord();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date endTime1 = null;
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime1 = null;
        try {
            endTime1 = sdf1.parse(endTime);
            startTime1 = sdf2.parse(startTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //缴费
        HCustomerManage hCustomerManage = hCustomerManageMapper.selectByPrimaryKey(customerId);
        String deptId = hCustomerManage.getDeptId();
        record.setStartTime(startTime1);
        record.setEndTime(endTime1);
        record.setDeptId(deptId);
        record.setId(FleaStringUtils.getGenerateUUID());
        record.setPersonName(hCustomerManage.getPersonName());
        record.setPersonPhone(hCustomerManage.getPersonPhone());
        record.setCreateUser(userId);
        record.setModifyUser(userId);
        Float cost1 = Float.valueOf(cost);
        record.setCost(cost1);
        int row = hCustomerPayRecordMapper.insertSelective(record);
        if (row <= 0) {
            return ServerResponse.createByErrorMessage("缴费失败");
        }

        //更新客户状态
        hCustomerManage.setStatus(Const.CustomerStatusEnum.D_CUSTOMER_STATUS_PAY.getCode());
        hCustomerManage.setStartTime(startTime1);
        hCustomerManage.setEndTime(endTime1);
        hCustomerManage.setCost(cost1);
        row = hCustomerManageMapper.updateByPrimaryKeySelective(hCustomerManage);
        if (row <= 0) {
            return ServerResponse.createByErrorMessage("客户状态更新失败");
        }
        return ServerResponse.createBySuccessMessage("缴费成功");

    }

    @Override
    public ServerResponse<HCustomerManage> save(String userId, String model) {
        ServerResponse<HCustomerManage> response;
        response = this.fieldValidate(model);

        if (!response.isSuccess()) {
            return response;
        }

        JSONObject model1 = response.getModel();
        HCustomerManage record = (HCustomerManage) model1.get("data");
        String deptId = record.getDeptId();
        //查询客户是否已经存在
        HCustomerManage hCustomerManage = hCustomerManageMapper.selectByDeptId(deptId);
        if (hCustomerManage != null) {
            return ServerResponse.createByErrorMessage("客户已存在，请的列表查看");
        }
        //添加客户
        HCustomerManage customerManage = new HCustomerManage();
        customerManage.setId(FleaStringUtils.getGenerateUUID());
        customerManage.setModifyUser(userId);
        customerManage.setCreateUser(userId);
        customerManage.setDeptId(record.getDeptId());
        //设置缴费状态 未缴费
        customerManage.setStatus(Const.CustomerStatusEnum.D_CUSTOMER_STATUS_NO_PAY.getCode());
        //设置到期时间
        customerManage.setEndTime(record.getEndTime());
        customerManage.setStartTime(record.getStartTime());
        customerManage.setPersonName(record.getPersonName());
        customerManage.setPersonPhone(record.getPersonPhone());
        int row = hCustomerManageMapper.insertSelective(customerManage);
        if (row <= 0) {
            return ServerResponse.createByErrorMessage("添加客户失败");
        }
        return ServerResponse.createBySuccessMessage("添加客户成功");
    }

    //字段验证
    private ServerResponse<HCustomerManage> fieldValidate(String model) {
        if (model == null) {
            ServerResponse.createByErrorMessage("model为空");
        }
        JSONObject jsonObject = JSON.parseObject(model);
        String personName = jsonObject.getString("personName");
        if (StringUtils.isBlank(personName)) {
            return ServerResponse.createByErrorMessage("联系人为空");
        }
        String personPhone = jsonObject.getString("personPhone");
        if (StringUtils.isBlank(personPhone)) {
            return ServerResponse.createByErrorMessage("联系电话为空");
        }
        //缴费的部门ID
        String deptId = jsonObject.getString("deptId");
        if (StringUtils.isBlank(deptId)) {
            return ServerResponse.createByErrorMessage("部门Id为空");
        }

        HCustomerManage record = new HCustomerManage();
        record.setPersonName(personName);
        record.setPersonPhone(personPhone);
        record.setDeptId(deptId);

        return ServerResponse.createBySuccess(record);
    }
}
